<template>
  <div class="mod-config">
    <el-form :inline="true" :model="device" @keyup.enter.native="search()">
      <el-form-item>
        <el-select 
          v-model="searchBy" 
          clearable 
          placeholder="请选择索引方式"
          @change="search()"
        >
          <el-option
            v-for="item in searchOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input 
          v-model="searchQuery" 
          :placeholder="getPlaceholder()"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="search()" type="primary" icon="el-icon-search">查询</el-button>
        <el-button type="danger" @click="UpdateHandle()"  :disabled="dataListSelections.length <= 0">批量修改设备运行状态</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
      :row-class-name="tableRowClassName"

    >
      <!-- 多选框 -->
      <el-table-column type="selection" header-align="center" align="center" width="50" />
      <el-table-column type="index" header-align="center" align="center" label="序号" width="80" />
      <el-table-column prop="deviceName" header-align="center" align="center" label="设备名称" />
      <el-table-column prop="deviceId" header-align="center" align="center" width="150" label="设备编号" />
      <el-table-column prop="lightStatus" header-align="center" align="center" width="100" label="亮灯状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.lightStatus === -1" type="danger" >故障</el-tag>
          <el-tag v-else-if="scope.row.lightStatus === 0" type="warning" size="big">待机</el-tag>
          <el-tag v-else-if="scope.row.lightStatus === 1" type="success" size="big">运行</el-tag>
          <!-- <span class="status-text" :style="getStatusStyle(scope.row.lightStatus)">
            {{ getStatusText(scope.row.lightStatus) }}
          </span> -->
        </template>
      </el-table-column>
      <el-table-column prop="lightStartTime" header-align="center" align="center" label="灯亮起始时间" />
      <el-table-column prop="lightTime" header-align="center" align="center" label="亮灯时长">
        
        <template slot-scope="scope" >
          <div class="light-duration">
            {{ calculateLightDuration(scope.row.lightStartTime) }}
          </div>
        </template>
      
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="180"  label="操作">
        <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.lightStatus" 
                  @change="(newVal) =>handleLightStatusChange(scope.row,newVal)">
                      <el-radio :label="-1" v-if="scope.row.lightStatus === 1" border style="color: red;">
                          <span class="light-status" :style="{ backgroundColor: device.lightStatus === -1 ? '#f56c6c' : '' }">设备故障</span>
                      </el-radio>
                      <el-radio :label="0" v-if="scope.row.lightStatus === 0" border disabled>
                          <span class="light-status" :style="{ backgroundColor: device.lightStatus === 0 ? '#e6a23c' : '' }">保养中</span>
                      </el-radio>
                      <el-radio :label="1" v-if="scope.row.lightStatus === -1" border disabled>
                          <span class="light-status" :style="{ backgroundColor: device.lightStatus === 1 ? '#67c23a' : '' }">正在维修</span>
                      </el-radio>
                  </el-radio-group>
              </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    />
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList" />
    <!-- 批量修改弹窗 -->
    <el-dialog
      :title="'批量修改状态'"
      :close-on-click-modal="false"
      :visible.sync="batchUpdateVisible"
      center
      width="460px"
                     >
      <el-form :model="batchUpdateForm" ref="batchUpdateFormRef" label-width="80px">
        <el-form-item label="灯的状态:" prop="lightStatus" label-width="120px">
          <template>
            <el-radio-group v-model="batchUpdateForm.lightStatus">
              <el-radio :label="-1">
                <span class="light-status" :style="{ backgroundColor: batchUpdateForm.lightStatus === -1 ? '#f56c6c' : '' }" >红灯</span>
              </el-radio>
              <el-radio :label="0">
                <span class="light-status" :style="{ backgroundColor: batchUpdateForm.lightStatus === 0 ? '#e6a23c' : '' }">黄灯</span>
              </el-radio>
              <el-radio :label="1">
                <span class="light-status" :style="{ backgroundColor: batchUpdateForm.lightStatus === 1 ? '#67c23a' : '' }">绿灯</span>
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchUpdateVisible = false">取消</el-button>
        <el-button type="primary" @click="batchUpdateSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import addOrUpdate from './operation-update.vue';
export default {
  // components: { addOrUpdate },
  data() {
    return {
      device: { name: '',lightStatus:'2',deviceId:'' },
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      batchUpdateVisible: false,
      batchUpdateForm: { lightStatus: null },
      timeTick: 0, // 触发响应式更新
      timer: null, // 定时器
      searchOptions: [],  
      searchBy: 'name',
      searchQuery: '',
      
    
    };
  } , mounted() {
    this.getDataList();
    this.timer = setInterval(() => {
      this.timeTick = Date.now(); // 每秒更新时间戳
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  activated() {
    this.getDataList();
  },
  methods: { 
    getPlaceholder() {
      return this.searchBy === 'name' ? '请输入设备名称' : '请输入设备编号';
    },
    tableRowClassName({row, rowIndex}) {
          const remainder = rowIndex % 4;
            if (remainder === 0) return 'warning-row';  // 第1行（索引0）
            if (remainder === 2) return 'success-row';  // 第3行（索引2）
            return '';  // 第2行（索引1）无颜色
        
      },
    dataFormSubmit(deviceId,status) {
      console.log(22222222)
          this.$http({
              url: this.$http.adornUrl(`/dss/operation/save`),
              method: 'post',
              data: this.$http.adornData({
                  'deviceId': deviceId,
                  'lightStatus': status
              })
          }).then(({data}) => {
              if (data && data.code === 0) {
                  this.$message({
                      message: '操作成功',
                      type: 'success',
                      duration: 1500,
                      onClose: () => {
                          this.visible = false;
                          this.$emit('refreshDataList');
                      }
                  });
              } else {
                  this.$message.error(data.msg);
              }
          });
      },
    handleLightStatusChange(row,newValue) {
          this.$confirm('是否要将灯的状态改变为选中的状态？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              // 用户点击确定，更新原始灯状态
              this.dataFormSubmit(row.deviceId,newValue)
          }).catch(() => {
              // 用户点击取消，恢复原始灯状态
              this.getDataList();
              this.device.lightStatus = this.originalLightStatus;
          });
      },
    search() {
      this.pageIndex = 1;
      this.getDataList();
    },
    getDataList() {
      this.$http({
          url: this.$http.adornUrl('/sys/dict/treeOne'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.searchOptions = data.options
         
        })
      console.log(1111); // 在网页控制台上输出
      this.dataListLoading = true; // 确认加载，显示加载圈
      this.$http({
        url: this.$http.adornUrl('/dss/operation/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          [this.searchBy]: this.searchQuery
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // // 新增 / 修改（控制新增或修改数据的弹窗）
    // addOrUpdateHandle(id) {
    //   console.log(1111111111);
    //   this.addOrUpdateVisible = true;
    //   this.$nextTick(() => {
    //     this.$refs.addOrUpdate.init(id);
    //   });
    // },
    // 计算亮灯时长
    calculateLightDuration(startTime) {
      // 强制依赖响应式数据 timeTick，触发重新计算
      this.timeTick; 
     // 当 `this.timeTick` 的值发生变化时，Vue 会检测到这个依赖，从而触发包含此函数的计算属性或方法的重新计算。
   // 通常用于实现动态更新时长计算的功能，比如每秒更新显示的时长。
      if (!startTime) return '0天 00小时:00分钟:00秒';
      const now = new Date();
      const start = new Date(startTime);
      const diff = now - start;
      const totalSeconds = Math.floor(diff / 1000);
      //Math.floor() 方法用于向下取整一个数，返回小于等于该数的最大整数。

      const days = Math.floor(totalSeconds / (24 * 3600));
      const hours = Math.floor((totalSeconds % (24 * 3600)) / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;

      return `${days}天 ${String(hours).padStart(2, '0')}小时:${String(minutes).padStart(2, '0')}分钟:${String(seconds).padStart(2, '0')}秒`;
    },
     // 批量修改处理
     UpdateHandle() {
      if (this.dataListSelections.length === 0) {
        this.$message.warning('请选择要批量修改的设备');
        return;
      }
      this.batchUpdateVisible = true;
      this.batchUpdateForm.lightStatus = null;
    },
  // 批量修改提交（确保修改后刷新数据）
  batchUpdateSubmit() {
    if (this.batchUpdateForm.lightStatus === null) {
      this.$message.warning('请选择要修改的状态');
      return;
    }
    const batchData = this.dataListSelections.map(item => ({
      deviceId: item.deviceId,
      lightStatus: this.batchUpdateForm.lightStatus
    }));
    if (batchData.length === 0) {
      this.$message.warning('请选择要修改的设备');
      return;
    }
    this.$http({
      url: this.$http.adornUrl('/dss/operation/batchSave'),
      method: 'post',
      data: this.$http.adornData({ operationList: batchData })
    }).then(({ data }) => {
      if (data && data.code === 0) {
        this.$message({
          message: '批量修改成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.batchUpdateVisible = false;
            this.getDataList(); // 修改后重新获取数据，触发时长计算
          }
        });
      } else {
        this.$message.error(data.msg);
      }
    });
  },
    // 亮灯状态文字转换
    getStatusText(status) {
      switch (status) {
        case -1: return '故障';
        case 0: return '待机';
        case 1: return '运行';
        default: return '';
      }
    },
    // 亮灯状态颜色样式
    getStatusStyle(status) {
      switch (status) {
        case -1: 
          return { 
            'background-color': '#ee280a', 
            'border-radius': '4px', 
            'width': '60px', 
            'height': '27px', 
            'display': 'inline-block',
            'margin-right': '4px'
          };
        case 0: 
          return { 
            'background-color': '#ffdd01', 
            'border-radius': '4px', 
            'width': '60px', 
            'height': '27px', 
            'display': 'inline-block',
            'margin-right': '4px'
          };
        case 1: 
          return { 
            'background-color': '#28ea0a', 
            'border-radius': '4px', 
            'width': '60px', 
            'height': '27px', 
            'display': 'inline-block',
            'margin-right': '4px'
          };
        default: return {};
      }
    }
  
  }
};
</script>
<style scoped>
.light-duration {
  /* 醒目样式 */
  font-size: 16px;       /* 字体大小 */
  color: #28ea0a;       /* 绿色 */
  font-weight: bold;    /* 加粗 */
  padding: 8px 16px;    /* 内边距 */
  border-radius: 8px;   /* 圆角 */
  background: rgba(255, 255, 255, 0.1); /* 半透明背景 */
}
</style>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
